﻿using Minecraft.CacheRedis;
using Minecraft.Config;
using System.Collections.Generic;
using Minecraft.Model;

namespace Minecraft.BLL.mysql
{

	/// <summary>
	/// 成就
	/// </summary>
	public class AchievementBLL : BaseBLL
	{
		private static RedisCacheHelper redisCacheHelper = new RedisCacheHelper();
		private static RedisKey redisKeyEnum = RedisKey.Achievements;

		public static AchievementModel GetSingleOrDefault(int playerId, out bool fromCache)
		{
			fromCache = false;
			string redisKey = RedisKeyHelper.GetRedisKeyName(redisKeyEnum, playerId.ToString());
			var cacheModel = redisCacheHelper.StringGet<AchievementModel>(redisKey);
			if (cacheModel != null)
			{
				fromCache = true;
				return cacheModel;
			}
			else
			{
				var model = new AchievementModel();
				model = GetSingleOrDefault(model, new KeyValuePair<string, int>(nameof(model.PlayerId), playerId));
				redisCacheHelper.StringSet(redisKey, model, CommonConfig.DefRedisExpiry);
				return model;
			}
		}


		/// <summary>
		/// 
		/// </summary>
		/// <param name="playerId"></param>
		/// <param name="fromCache"></param>
		/// <returns></returns>
		public static List<AchievementModel> GetList(int playerId, out bool fromCache)
		{
			fromCache = false;
			string redisKey = RedisKeyHelper.GetRedisKeyName(redisKeyEnum, playerId.ToString());
			var cacheList = redisCacheHelper.StringGet<List<AchievementModel>>(redisKey);
			if (cacheList != null)
			{
				fromCache = true;
				return cacheList;
			}
			else
			{
				var model = new AchievementModel();
				var list = GetList(model, new KeyValuePair<string, int>(nameof(model.PlayerId), playerId));
				redisCacheHelper.StringSet(redisKey, list, CommonConfig.DefRedisExpiry);
				return list;
			}
		}

		/// <summary>
		/// 批量更新
		/// </summary>
		/// <param name="list"></param>
		/// <param name="playerId"></param>
		/// <param name="isCacheAfterDbOpt">缓存后是否进行数据库操作</param>
		public static bool BatchUpdate(List<AchievementModel> list,int playerId, bool isCacheAfterDbOpt = false)
		{
			string redisKey = RedisKeyHelper.GetRedisKeyName(redisKeyEnum, playerId.ToString());
			redisCacheHelper.StringSet(redisKey, list, CommonConfig.DefRedisExpiry);
			if (isCacheAfterDbOpt)
			{
				AchievementModel model;
				return BatchUpdate(list, new KeyValuePair<string, int>(nameof(model.PlayerId), playerId));
			}
			return true;
		}
	}
}
